package main
import (
    "github.com/hoisie/web"
    "labix.org/v2/mgo"
    "io/ioutil"
    "io"
    "os"
    "time"
    "encoding/json"
    "text/template"
)

var (
    job_queue chan func()
    session,_ = mgo.Dial("localhost")
    db = session.DB("ATT")
    Analyze_Database = db.C("Analyze")
    Job_Database = db.C("Job")
)

// Handle GET request, just render the static file
func index(ctx *web.Context) {
    data,err := ioutil.ReadFile("index.html")
    if err != nil {
	panic(err)
    }

    ctx.ResponseWriter.Write(data)
}

func save_upload_to_file(ctx *web.Context, file_id string) string{
    err := ctx.Request.ParseMultipartForm(32 << 20)
    if err != nil {
	panic(err)
    }

    file,handler,err := ctx.Request.FormFile(file_id)
    if err != nil {
	panic(err)
    }
    defer file.Close()

    dest_file_name := "upload/" + handler.Filename
    dest_file,err := os.Create(dest_file_name)
    if err != nil {
	panic(err)
    }
    defer dest_file.Close()

    io.Copy(dest_file, file)
    return dest_file_name
}

func Marshal(data interface{}) string {
    result,_ := json.Marshal(data)
    return string(result)
}

// Handle file upload
func upload(ctx *web.Context) {
    result_3G_file := save_upload_to_file(ctx,"3G")
    result_wifi_file := save_upload_to_file(ctx,"WIFI")
    render_data := Analyze(result_3G_file,result_wifi_file)

    t,err := template.ParseFiles("Template.html")
    t.Funcs(template.FuncMap{"Marshal":Marshal})
    if err != nil {
	panic(err)
    }
    Analyze_Database.Insert(render_data)
    err = t.Execute(ctx.ResponseWriter, render_data)
    if err != nil {
	panic(err)
    }
}

// Upload APK file and give ananlyze result
func apk_upload(ctx *web.Context) {
    // Download APK File
    // apk_file := save_upload_to_file(ctx,"apk")
    timeout := time.After(time.Second * 5)
    finish  := make(chan int)
    go func() {
	// TODO: Add tasks
	finish <- 1
    }()
    select {
    case <- finish:
	ctx.WriteString("Finish Upload APK File")
    case <- timeout:
	ctx.WriteString("Error: Buffer is full")
    }
}

func main() {
    go Worker()
    Add_Task("CloudMusic_official_1.3.2.apk")
    <-job_queue
    return
    job_queue = make(chan func(), 100)
    web.Get("/index", index)
    web.Post("/upload", upload)
    web.Post("/uploadAPK",apk_upload)
    web.Run("0.0.0.0:22001")
}
